<?php
/*
+--------------------------------------------------------------------------
|   phpBIZbiz v 2.0 full version
|   ========================================
|   by taft@wjl.cn
|   http://www.phpbiz.cn
|   all rights reserved
+---------------------------------------------------------------------------
|
|   > 
|   > 最后修改日期：2005-9-9
|   > 
|
+--------------------------------------------------------------------------
*/

class FUNC
{

	function parse_income()
    {
    	global $_GET, $_POST, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;
    	$return = array();
    	
		if( is_array($_GET) )
		{
			while( list($k, $v) = each($_GET) )
			{
				if( is_array($_GET[$k]) )
				{
					while( list($k2, $v2) = each($_GET[$k]) )
					{
						$return[$k][ $this->clean_key($k2) ] = $this->clean_value($v2);
					}
				}
				else
				{
					$return[$k] = $this->clean_value($v);
				}
			}
		}
		
		// Overwrite GET data with post data
		
		if( is_array($_POST) )
		{
			while( list($k, $v) = each($_POST) )
			{
				if ( is_array($_POST[$k]) )
				{
					while( list($k2, $v2) = each($_POST[$k]) )
					{
						$return[$k][ $this->clean_key($k2) ] = $this->clean_value($v2);
					}
				}
				else
				{
					$return[$k] = $this->clean_value($v);
				}
			}
		}
		
		//----------------------------------------
		// Sort out the accessing IP
		// (Thanks to Cosmos and schickb)
		//----------------------------------------
		
		$addrs = array();
		
		foreach( array_reverse( explode( ',', $HTTP_X_FORWARDED_FOR ) ) as $x_f )
		{
			$x_f = trim($x_f);
			
			if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f ) )
			{
				$addrs[] = $x_f;
			}
		}
		
		$addrs[] = $_SERVER['REMOTE_ADDR'];
		$addrs[] = $HTTP_PROXY_USER;
		$addrs[] = $REMOTE_ADDR;
		
		//header("Content-type: text/plain"); print_r($addrs); print $_SERVER['HTTP_X_FORWARDED_FOR']; exit();
		
		$return['IP_ADDRESS'] = $this->select_var( $addrs );
												 
		// Make sure we take a valid IP address
		
		$return['IP_ADDRESS'] = preg_replace( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS'] );
		
		$return['request_method'] = ( $_SERVER['REQUEST_METHOD'] != "" ) ? strtolower($_SERVER['REQUEST_METHOD']) : strtolower($REQUEST_METHOD);
		
		return $return;
	}
	function clean_value($val)
    {
    	
    	if ($val == "")
    	{
    		return "";
    	}
    	
    	$val = str_replace( "&#032;", " ", $val );
     	
    	$val = str_replace( "&"            , "&amp;"         , $val );
    	$val = str_replace( "<!--"         , "&#60;&#33;--"  , $val );
    	$val = str_replace( "-->"          , "--&#62;"       , $val );
    	$val = preg_replace( "/<script/i"  , "&#60;script"   , $val );
    	$val = str_replace( ">"            , "&gt;"          , $val );
    	$val = str_replace( "<"            , "&lt;"          , $val );
    	$val = str_replace( "\""           , "&quot;"        , $val );
    	//$val = preg_replace( "/\n/"        , "<br>"          , $val ); // Convert literal newlines
    	$val = preg_replace( "/\\\$/"      , "&#036;"        , $val );
    	//$val = preg_replace( "/\r/"        , ""              , $val ); // Remove literal carriage returns
    	$val = str_replace( "!"            , "&#33;"         , $val );
    	$val = str_replace( "'"            , "&#39;"         , $val ); // IMPORTANT: It helps to increase sql query safety.
    	
    	// Ensure unicode chars are OK
    	
    	if ( $this->allow_unicode )
		{
			$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
		}
		
		// Strip slashes if not already done so.
		
    	if ( $this->get_magic_quotes )
    	{
    		$val = stripslashes($val);
    	}
    	
    	// Swop user inputted backslashes
    	
    	$val = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $val ); 
    	
    	return $val;
    }
    
	function select_var($array)
	{
    	
    	if ( !is_array($array) ) return -1;
    	
    	ksort($array);
    	    	
    	$chosen = -1;  // Ensure that we return zero if nothing else is available
    	
    	foreach ($array as $k => $v)
    	{
    		if (isset($v))
    		{
    			$chosen = $v;
    			break;
    		}
    	}
    	
    	return $chosen;
    }
    function clean_key($key)
	{
    
    	if ($key == "")
    	{
    		return "";
    	}
    	$key = preg_replace( "/\.\./"           , ""  , $key );
    	$key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
    	$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
    	return $key;
    }
	
	//**********************************************/
	// rebuild_config:
	//
	// rewrites overall the config file
	//
	//**********************************************/
	
	function rebuild_config( $new = "" )
	{
		global $INCOME, $ADMIN ,$CONF,$DB;
		
		define('ROOT_PATH', $CONF['base_dir']);

		//-----------------------------------------
		// Check to make sure this is a valid array
		//-----------------------------------------
		
		if (! is_array($new) )
		{
			$ADMIN->error($ADMIN->lang['error_write_config']);
		}
		
		//-----------------------------------------
		// Do we have anything to save out?
		//-----------------------------------------
		
		if ( count($new) < 1 )
		{
			return "";
		}
		
		//-----------------------------------------
		// Get an up to date copy of the config file
		//-----------------------------------------
		
		require ROOT_PATH.'conf_global.php';
		
		//-----------------------------------------
		// Rebuild the $INFO hash
		//-----------------------------------------
		
		foreach( $new as $k => $v )
		{
			// Update the old...
			
			$v = preg_replace( "/'/", "\\'" , $v );
			$v = preg_replace( "/\r/", ""   , $v );
			
			$CONF[ $k ] = $v;
		}	

		//-----------------------------------------
		// Rename the old config file
		//-----------------------------------------
		
		@rename( ROOT_PATH.'conf_global.php', ROOT_PATH.'conf_global-bak.php' );
		@chmod( ROOT_PATH.'conf_global-bak.php', 0777);
		
		//-----------------------------------------
		// Rebuild the old file
		//-----------------------------------------
		
		ksort($CONF);
		
		$file_string = "<?php\n";
		
		
		foreach( $CONF as $k => $v )
		{
			
	    	$DB -> db_query( "REPLACE INTO `biz_global_configure` (`key`, `value`,`last_time`) VALUES ('$k', '$v','".time()."')" );
		
            if( strpos($k,"reg_")!==false ) continue;
			if( strpos($k,"att_")!==false ) continue;
			if( strpos($k,"fee_")!==false ) continue;
			if( strpos($k,"repute_")!==false ) continue;
			if( strpos($k,"account_")!==false) continue;
			
			$file_string .= '$CONF['."'".$k."'".']'."\t\t\t=\t'".$v."';\n";
		}
		
		$file_string .= "\n".'?'.'>';   
		
		if ( $fh = fopen( ROOT_PATH.'conf_global.php', 'w' ) )
		{
			fputs ($fh, $file_string, strlen($file_string) );
			fclose($fh);
		}
		else
		{
			$ADMIN->error($ADMIN->lang['fatal_write_config']);
		}
		
		return $CONF;
		
	}


}

class cache
{
	function DB_Cache($sql)
	{
	    global $DB;
	    $bizdb=array();
	    $query=$DB->db_query($sql);
	    while($rt=$DB->db_fetch_row($query,MYSQL_NUM))
		{
		$bizdb[]=$rt;
		}
	    return $this -> array_export($bizdb);
    }
 
    function array_export($array,$c=1,$t='',$var='')
	{
		$c && $var="array(\r\n";
		$t.="  ";
		if(is_array($array))
		{
		    foreach($array as $key => $value)
		    {
			    $var.="$t'".addslashes($key)."'=>";
			    if(is_array($value))
				{
				    $var.="array(\r\n";
				    $var=$this->array_export($value,0,$t,$var);
				    $var.="$t),\r\n";
			    }else{
				    $var.="'".addslashes($value)."',\r\n";
			    }
		     }
	     }
	     if($c)
	     {
		   $var.=")";
	     }
	return $var;
    }

	function write_cache($filename,$data,$method="rb+",$iflock=1)
	{
		touch($filename);
		$handle=fopen($filename,$method);
		if($iflock)
		{
			flock($handle,LOCK_EX);
		}
		fputs($handle,$data);
		if($method=="rb+") ftruncate($handle,strlen($data));
		fclose($handle);
	}

	function cache_level()
	{
		global $DB;
		$cache_file = ROOT_PATH.'cache/level_cache.php';
	
		$bizcache="\$_LEVEL=array(\r\n";
		$bizcache.="'level'=>".$this->DB_Cache("SELECT level_id,property_name,fee FROM biz_seller_property ORDER BY rank_id").",\r\n\r\n";
		$bizcache.=");\r\n";
		$this->write_cache($cache_file,"<?php\r\n$bizcache?>");// 写php cache文件
		include $cache_file;
		$bizcache="\$_LEVEL=array(\r\n";
		foreach($_LEVEL['level'] as $k =>$v)
		{
			$bizcache.= $v[0]."=>array('".$v[1]."','".$v[2]."'),\r\n";
		}
		$bizcache.=");\r\n";
		$this->write_cache($cache_file,"<?php\r\n$bizcache?>");// 写php cache文件
		
		return;
	}
	function cache_fee()
	{
		global $DB;
		$cache_file = ROOT_PATH.'cache/fee_cache.php';
		$r = $DB -> db_once("SELECT `key`,`value` FROM biz_global_configure WHERE `key`= 'fee_db' ");
		$feedb = unserialize($r[value]);
		$str = "\$feedb=array(";
		foreach($feedb as $k => $v)
		{
			$str .= "'$k'=>".intval($v).",\t\t\n";
		}
		$str .=");\t\n";
		$this->write_cache($cache_file,"<?php\r\n$str?>");
	}
}
?>